import {ProForm, ProFormText} from '@ant-design/pro-components';
import {App, Button, Col, Flex, Form, Progress, Row} from 'antd';
import {keys, values} from 'lodash-es';
import React, {FC} from 'react';
import zxcvbn from 'zxcvbn';

import {strengthMeterOptions} from '@/components/StrengthMeter/config';
import styles from '@/components/StrengthMeter/index.module.less';
import {encryptionAesPsd, formatPerfix, initUserAuthority, isSuccess, setLocalStorageItem, timeFix} from '@/utils';
import {INTERNATION, LOCAL_STORAGE, ROUTES} from '@/utils/enums';
import {history, Icon, useIntl} from '@@/exports';

import defaultSettings from '../../../../config/defaultSettings';
import {useRequest} from "ahooks";
import {Regist} from "@/services/logic/login";
import type {InitialStateTypes} from "@/utils/types";
import dayjs from "dayjs";
import {useModel} from "@umijs/max";

type RegisterProps = {
  user_name: string;
  work_no: string;
  cn_name: string;
  phone: string;
  password: string;
};

const Register: FC = ({toLogin}) => {
  const {formatMessage} = useIntl();
  // 获取 form 实例
  const [form] = Form.useForm();
  // 监听密码的改变 @ts-ignore
  const password = Form.useWatch('password', {form});
  // 初始化状态
  const {initialState, setInitialState} = useModel('@@initialState');
  // hooks 调用
  const {notification, message} = App.useApp();

  /**
   * @description: 监听密码强度相应变化
   * @param {string} password
   * @author: YoungYa
   */
  const watchStrength = (password: string): number => {
    console.log(password);
    const analysisValue = zxcvbn(password)
    // score得分只有0~4，且只有整数范围并没有小数
    return (analysisValue.score + 1) * 20
  }

  const FormItems = [
    {
      name: 'user_name',
      fieldProps: {
        size: 'large',
        prefix: <Icon icon="ri:user-line" className={'prefixIcon'}/>,
      },
      placeholder: formatMessage({
        id: formatPerfix(ROUTES.REGISTER, 'user_name'),
      }),
      rules: [
        {
          required: true,
          message: formatMessage({
            id: formatPerfix(ROUTES.REGISTER, 'user_name.required'),
          }),
        },
      ],
      autocomplete: 'off',
      initialValue: 'user1',
    },
    {
      name: 'work_no',
      fieldProps: {
        size: 'large',
        prefix: <Icon icon="openmoji:office-worker" className={'prefixIcon'}/>,
      },
      placeholder: formatMessage({id: formatPerfix(ROUTES.REGISTER, 'work_no')}),
      rules: [
        {
          required: true,
          message: formatMessage({id: formatPerfix(ROUTES.REGISTER, 'work_no.required')}),
        },
      ],
      autocomplete: 'off',
      initialValue: '5120210000',
    },
    {
      name: 'cn_name',
      fieldProps: {
        size: 'large',
        prefix: <Icon icon="icon-park-outline:chinese" className={'prefixIcon'}/>,
      },
      placeholder: formatMessage({id: formatPerfix(ROUTES.REGISTER, 'cn_name')}),
      rules: [
        {
          required: true,
          message: formatMessage({id: formatPerfix(ROUTES.REGISTER, 'cn_name.required')}),
        },
      ],
      autocomplete: 'off',
      initialValue: '张三',
    },
    {
      name: 'phone',
      fieldProps: {
        size: 'large',
        prefix: <Icon icon="ri:smartphone-line" className={'prefixIcon'}/>,
      },
      placeholder: formatMessage({id: formatPerfix(ROUTES.LOGIN, 'type.mobile.phone')}),
      rules: [
        {
          required: true,
          message:
            formatMessage({id: INTERNATION.PLACEHOLDER}) +
            formatMessage({id: formatPerfix(ROUTES.LOGIN, 'type.mobile.phone')}),
        },
        {
          pattern: /^1\d{10}$/,
          message: formatMessage({id: formatPerfix(ROUTES.LOGIN, 'type.mobile.phone.rules')}),
        },
      ],
      autocomplete: 'off',
      initialValue: '13000000000',
    },
    {
      name: 'password',
      fieldProps: {
        size: 'large',
        prefix: <Icon icon="ri:lock-line" className={'prefixIcon'}/>,
        type: 'password',
      },
      placeholder: formatMessage({
        id: formatPerfix(ROUTES.REGISTER, 'password'),
      }),
      rules: [
        {
          required: true,
          message: formatMessage({
            id: formatPerfix(ROUTES.REGISTER, 'password.required'),
          }),
        },
      ],
      autocomplete: 'off',
      initialValue: 'abc123456',
    },
  ]
  /**
   * @description: 用户注册接口
   * @param {RegisterProps} params
   * @author: YoungYa
   * @date 2024/11/24
   */
  const {run, loading} = useRequest(
    async (params) => await Regist(params),
    {
      // 如果设置了 options.manual = true，则 useRequest 不会默认执行，需要通过 run 来触发执行
      manual: true,
      onSuccess: async ({code, data}) => {
        if (isSuccess(code)) {
          message.success("注册成功");
          toLogin();
        }
      },
    }
  )

  const handleRegister = (values: RegisterProps) => {
    try {
      values.password = encryptionAesPsd(values.password);
      run(values)
    } catch (error) {
      message.error(error)
    }
  }

  return (
    <div className={'ant-pro-form-login-container'}>
      <Flex justify={'center'}>
        <img alt="logo" src="/logo.png" width={44}/>
        <span className={'ant-pro-form-login-title'}>{defaultSettings.title}</span>
      </Flex>
      <ProForm<RegisterProps>
        form={form}
        loading={loading}
        className={'ant-pro-form-login-main '}
        submitter={{
          render: ({submit}) => ([
            <Button type="primary" style={{width: '50%'}} key="register" onClick={() => submit()}>
              {formatMessage({id: formatPerfix(ROUTES.REGISTER)})}
            </Button>,
            <Button type="link" key="login" onClick={() => toLogin()}>
              {formatMessage({id: formatPerfix(ROUTES.LOGIN)})}
            </Button>,
          ]),
        }}
        onFinish={handleRegister}
      >
        {FormItems.map((item) => (
          <ProFormText key={item.name} {...item}/>
        ))}
        <div className={styles['process-steps']}>
          <Progress
            percent={password ? watchStrength(password) : 0}
            steps={5}
            strokeColor={values(strengthMeterOptions)}
            showInfo={false}
          />
        </div>
        <Row justify="space-around" className={styles['process-steps']}>
          {
            keys(strengthMeterOptions).map((value: string) =>
              <Col span={4} key={value}>{formatMessage({id: `components.StrengthMeter.${value}`})}</Col>)
          }
        </Row>
      </ProForm>

    </div>
  );
};

export default Register;
